package com.example.androidproject.ui.fragment;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ZipUtils;
import com.example.androidproject.R;
import com.example.androidproject.ui.base.IBaseFragment;
import com.hyg.base.ui.base.BasePresenter;
import com.hyg.base.ui.common.FragmentContainerActivity;
import com.hyg.common.utils.FileUtils;
import com.hyg.common.utils.ShellUtils;
import com.hyg.common.utils.ToastUtils;

import java.io.IOException;
import java.lang.reflect.Method;

import butterknife.OnClick;

/**
 * Author: HuangYuGuang
 * Date: 2024/7/27
 */
public class ShellTestFragment extends IBaseFragment {
    private String TAG = "ShellTestFragment";

    public static void launch(Activity from){
        FragmentContainerActivity.getInstance().launch(from, ShellTestFragment.class);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_shell_test;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initViewAndData() {
        String updateFile = "/sdcard/Download/4G_updata.zip";
        if(FileUtils.isFileExists(updateFile)){
            try {//下载的驱动更新包解压缩
                ZipUtils.unzipFile("/sdcard/Download/4G_updata.zip","/sdcard/Download/");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void checkVersion(){
        //驱动版本
        String v1 = getProperty("gsm.version.ril-impl","V0");//Quectel_Android_RIL_Driver_V3.6.24_master_Release_20231211_10_47
        //基带版本
        String v2 = getProperty("gsm.version.baseband","V0");//EC200ACNDAR01A14M16
        if(!("Quectel_Android_RIL_Driver_V3.6.24_master_Release_20231211_10_47".equals(v1) && "EC200ACNDAR01A14M16".equals(v2))){
            new AdbTask().execute();
        }else {
            ToastUtils.show("已经是最新版");
        }
    }

    @OnClick({R.id.btn1})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn1:
                checkVersion();
                break;
        }
    }

    class AdbTask extends AsyncTask<String, String, Boolean> {

        @Override
        protected void onPreExecute() {
            showLoading("正在升级...");
        }

        @Override
        protected Boolean doInBackground(String... strings) {
            sendShellCmd("mount -o rw,remount /system");//目录设为可写
            sendShellCmd("cp -r /sdcard/Download/libreference-ril-EC200A.so /system/lib64/");
            sendShellCmd("mount -o rw,remount /data");//目录设为可写
            sendShellCmd("cp -r /sdcard/Download/QDloader /data/");
            sendShellCmd("cp -r /sdcard/Download/BinFile.bin /data/");
            sendShellCmd("chmod 777 -R /data/QDloader");
            sendShellCmd("chmod 777 -R /data/BinFile.bin");
            boolean success = sendShellCmd("/data/QDloader -f /data/BinFile.bin");//升级4G模块，耗时大概一分钟
            if(!success){//升级失败再重试2次
                SystemClock.sleep(500);
                success = sendShellCmd("/data/QDloader -f /data/BinFile.bin");
                if(!success){
                    SystemClock.sleep(500);
                    success = sendShellCmd("/data/QDloader -f /data/BinFile.bin");
                }
            }
            Log.e(TAG,"--------------------------------------------------------------------");
            return success;
        }

        @Override
        protected void onPostExecute(Boolean s) {
            hideLoading();
            if(s){//升级成功后需要重启
                ToastUtils.show("升级成功！！！！！");
                Log.e(TAG,"升级成功！！！！！");
                checkVersion();
            }else {
                ToastUtils.show("升级失败！！！！！");
                Log.e(TAG,"升级失败！！！！！");
            }
        }
    }

    /**
     * 发送shell命令
     * @param cmd 有些命令需要前面加 busybox
     */
    private boolean sendShellCmd(String cmd){
        Log.e(TAG,"-> " + cmd);
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(cmd,true);
        if(commandResult.result == 0){
            Log.e(TAG,"<- successMsg=" + commandResult.result);
        }else {
            Log.e(TAG,String.format("<- errCode=%s, errorMsg=%s",commandResult.result,commandResult.errorMsg));
        }
        return commandResult.result == 0;
    }

    public String getProperty(String key, String defaultValue) {
        String value = defaultValue;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, key, defaultValue));
            Log.e(TAG,key + " = " + value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return value;
        }
    }

}
